<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="React,高阶组件," />










<meta name="description" content="前言学习react已经有一段时间了，期间在阅读官方文档的基础上也看了不少文章，但感觉对很多东西的理解还是不够深刻，因此这段时间又在撸一个基于react全家桶的聊天App（现在还在瞎78写的阶段，在往这个聊天App这个方向写），通过实践倒是对react相关技术栈有了更为深刻的理解。在使用react-redux的过程中，发现connect好像还挺有意思的，也真实感受到了高阶组件所带来的便利，出于自己写">
<meta name="keywords" content="React,高阶组件">
<meta property="og:type" content="article">
<meta property="og:title" content="React高阶组件的那些事，了解一下？">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/05/06/React高阶组件的那些事，了解一下？/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="前言学习react已经有一段时间了，期间在阅读官方文档的基础上也看了不少文章，但感觉对很多东西的理解还是不够深刻，因此这段时间又在撸一个基于react全家桶的聊天App（现在还在瞎78写的阶段，在往这个聊天App这个方向写），通过实践倒是对react相关技术栈有了更为深刻的理解。在使用react-redux的过程中，发现connect好像还挺有意思的，也真实感受到了高阶组件所带来的便利，出于自己写">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-12-19T13:24:18.035Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="React高阶组件的那些事，了解一下？">
<meta name="twitter:description" content="前言学习react已经有一段时间了，期间在阅读官方文档的基础上也看了不少文章，但感觉对很多东西的理解还是不够深刻，因此这段时间又在撸一个基于react全家桶的聊天App（现在还在瞎78写的阶段，在往这个聊天App这个方向写），通过实践倒是对react相关技术栈有了更为深刻的理解。在使用react-redux的过程中，发现connect好像还挺有意思的，也真实感受到了高阶组件所带来的便利，出于自己写">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/05/06/React高阶组件的那些事，了解一下？/"/>





  <title>React高阶组件的那些事，了解一下？ | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/06/React高阶组件的那些事，了解一下？/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">React高阶组件的那些事，了解一下？</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-06T13:25:05+08:00">
                2018-05-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/React/" itemprop="url" rel="index">
                    <span itemprop="name">React</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,898
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  15
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h4><p>学习react已经有一段时间了，期间在阅读官方文档的基础上也看了不少文章，但感觉对很多东西的理解还是不够深刻，因此这段时间又在撸一个基于react全家桶的聊天App（现在还在瞎78写的阶段，在往这个聊天App这个方向写），通过实践倒是对react相关技术栈有了更为深刻的理解。在使用react-redux的过程中，发现connect好像还挺有意思的，也真实感受到了高阶组件所带来的便利，出于自己写项目本身就是为了学习的目的，因此对高阶组件又进行了一番学习。写下这篇文章主要是对高阶组件的知识进行一个梳理与总结，如有错误疏漏之处，敬请指出，不胜感激。</p>
<h2 id="初识高阶组件"><a href="#初识高阶组件" class="headerlink" title="初识高阶组件"></a>初识高阶组件</h2><p><em>要学习高阶组件首先我们要知道的就是高阶组件是什么，解决了什么样的问题。</em></p>
<p>React官方文档的对高阶组件的说明是这样的:</p>
<blockquote>
<p>A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, perse. They are a pattern that emerges from React’s compositional nature.</p>
</blockquote>
<p>从上面的说明我们可以看出，react 的高阶组件并不是 react API 的一部分，它源自于 react 的生态。</p>
<p>简单来说，一个高阶组件就是一个函数，它接受一个组件作为输入，然后会返回一个新的组件作为结果，且所返回的新组件会进行相对增强。值得注意的是，我们在这说的组件并不是组件实例，而是一个组件类或者一个无状态组件的函数。就像这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">removeUserProp</span>(<span class="params">WrappedComponent</span>) </span>&#123;</span><br><span class="line"><span class="comment">//WrappingComponent这个组件名字并不重要，它至少一个局部变量，继承自React.Component</span></span><br><span class="line">    <span class="keyword">return</span> <span class="class"><span class="keyword">class</span> <span class="title">WrappingComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">        render() &#123;</span><br><span class="line"><span class="comment">// ES6的语法，可以将一个对象的特定字段过滤掉</span></span><br><span class="line">            <span class="keyword">const</span> &#123;user, ...otherProps&#125; = <span class="keyword">this</span>.props</span><br><span class="line">            <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">WrappedComponent</span> &#123;<span class="attr">...otherProps</span>&#125; /&gt;</span></span></span><br><span class="line"><span class="xml">        &#125;</span></span><br><span class="line"><span class="xml">      &#125;</span></span><br><span class="line"><span class="xml">&#125;</span></span><br></pre></td></tr></table></figure>
<p>了解设计模式的大佬们应该发现了，它其实就是的设计模式中的装饰者模式在react中的应用，它通过组合的方式从而达到很高的灵活程度和复用。<br>就像上面的代码，我们定义了一个叫做 removeUserProp 的高阶组件，传入一个叫做 WrappedComponent 的参数（代表一个组件类），然后返回一个新的组件 ，新的组件与原组件并没有太大的区别，只是将原组件中的 prop 值 user 给剔除了出来。</p>
<p>有了上面这个高阶组件的，当我们不希望某个组件接收到 user 时，我们就可以将这个组件作为参数传入 removeUserProp() 函数中，然后使用这个返回的组件就行了：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> NewComponent = removeUserProp(OldComponent)</span><br></pre></td></tr></table></figure>
<p>这样 NewComponent 组件与 OldComponent 组件拥有完全一样的行为，唯一的区别就在于传入的name属性对这个组件没有任何作用，它会自动屏蔽这个属性。也就是说，我们这个高阶组件成功的为传入的组件增加了一个屏蔽某个prop的功能。</p>
<p>那么明白了什么是高阶组件后，我们接下来要做的是，弄清楚高阶组件主要解决的问题，或者说我们为什么需要高阶组件？总结起来主要是以下两个方面：</p>
<ol>
<li>代码重用<blockquote>
<p>在很多情况下，react组件都需要共用同一个逻辑，我们在这个时候就可以把这部分共用的逻辑提取出来，然后利用高阶组件的形式将其组合，从而减少很多重复的组件代码。</p>
</blockquote>
</li>
</ol>
<p>2.修改React组件的行为</p>
<blockquote>
<p>很多时候有些现成的react组件并不是我们自己撸出来的，而是来自于GitHub上的大佬们的开源贡献，而当我们要对这些组件进行复用的时候，我们往往都不想去触碰这些组件的内部逻辑，这时我们就能通过高阶组件产生新的组件满足自身需求，同时也对原组件没有任何损害。</p>
</blockquote>
<p>现在我们对高阶组件有了一个较为直观的认识，知道了什么是高阶组件以及高阶组件的主要用途。接下来我们就要具体了解高阶组件的实现方式以及它的具体用途了。</p>
<h3 id="高阶组件的实现分类"><a href="#高阶组件的实现分类" class="headerlink" title="高阶组件的实现分类"></a>高阶组件的实现分类</h3><p>对于高阶组件的实现方式我们可以根据作为参数传入的组件与返回的新组件的关系将高阶组件的实现方式分为以下两大类：</p>
<ul>
<li>代理方式的高阶组件</li>
<li>继承方式的高阶组件<h2 id="代理方式的高阶组件"><a href="#代理方式的高阶组件" class="headerlink" title="代理方式的高阶组件"></a>代理方式的高阶组件</h2>从高阶组件的使用频率来讲，我们使用的绝大多数的高阶组件都是代理方式的高阶组件，如react-redux中的connect，还有我们在上面所实现的那个removeUserProp。这类高阶组件的特点是返回的新组件类直接继承于 React.Component 类。新组建在其中扮演的角色是一个传入参数组件的代理，在新组建的render函数中，把被包裹的组件渲染出来。在此过程中，除了高阶组件自己需要做的工作，其他的工作都会交给被包裹的组件去完成。</li>
</ul>
<p>代理方式的高阶组件具体而言，应用场景可以分为以下几个：</p>
<ul>
<li>操作prop</li>
<li>通过ref获取组件实例</li>
<li>抽取状态</li>
<li>包装组件</li>
</ul>
<h3 id="控制prop"><a href="#控制prop" class="headerlink" title="控制prop"></a>控制prop</h3><p>代理类型的高阶组件返回的新组件时，渲染过程也会被新组建的render函数所控制，而在此过程中，render函数相对于一个代理，完全决定该如何使用被包裹在其中的组件。在render函数中，this.props包含了新组件接受到的所有prop。因此最直观的用法就是接受到props，然后进行任何读取，增减，修改等控制props的自定义操作。<br>就比如我们上面的那个示例，就做到了删除prop的功能，当然我们也能实现一个添加prop的高阶组件：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">addNewProp</span>(<span class="params">WrappedComponent, newProps</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="class"><span class="keyword">class</span> <span class="title">WrappingComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">        render() &#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">WrappedComponent</span> &#123;<span class="attr">...thisProps</span>&#125; &#123;<span class="attr">...newProps</span>&#125; /&gt;</span></span></span><br><span class="line"><span class="xml">        &#125;</span></span><br><span class="line"><span class="xml">      &#125;</span></span><br><span class="line"><span class="xml">&#125;</span></span><br></pre></td></tr></table></figure>
<p>这个addNewProp高阶组件与我们最开始举例的removeUserProp高阶组件在实现上并无太大的区别。唯一区别较大的就是我们传入的参数除了WrappedComponent组件类外，还新增了newProps参数。这样的高阶组件在复用性方面会跟友好，我们可以利用这样一个高阶组件给不同的组件添加不同的新属性，比如这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> FirstComponent = addNewProp(OldComponent,&#123;<span class="attr">num</span>: First&#125;)</span><br><span class="line"><span class="keyword">const</span> LastComponent = addNewProp(NewComponent,&#123;<span class="attr">num</span>: Last&#125;)</span><br></pre></td></tr></table></figure>
<p>在上面的代码中，我们实现了让两个完全不同的组件分别通过高阶组件生成了两个完成不同的新的组件，而这其中唯一相同的是都添加了一个属性值，且这个属性还不相同。从上面的代码我们也不难发现，高阶组件可以重用在不同组件上，减少了重复的代码。当需要注意的是，在修改和删除 Props的时候，除非由特殊的要求，否则最好不要影响到原本传递给普通组件的 Props。</p>
<h3 id="通过ref获取组件实例"><a href="#通过ref获取组件实例" class="headerlink" title="通过ref获取组件实例"></a>通过ref获取组件实例</h3><p>我们可以通过ref获取组件实例，但值得注意的是，React官方不提倡访问ref，我们只是讨论一下这个技术的可行性。在此我们写一个refsHOC的高阶组件，可以获得被包裹组件的ref，从而根据ref直接操纵被包裹组件的实例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">refsHOC</span>(<span class="params">WrappedComponent</span>) =&gt; </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="class"><span class="keyword">class</span> <span class="title">HOCComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">    <span class="keyword">constructor</span>() &#123;</span><br><span class="line">      <span class="keyword">super</span>(...arguments)</span><br><span class="line">      <span class="keyword">this</span>.linkRef = <span class="keyword">this</span>.linkRef.bind(<span class="keyword">this</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    linkRef(wrappedInstance) &#123;</span><br><span class="line">      <span class="keyword">this</span>._root = wrappedInstance</span><br><span class="line">    &#125;</span><br><span class="line">    render() &#123;</span><br><span class="line">      <span class="keyword">const</span> props = &#123;...this.props, <span class="attr">ref</span>: <span class="keyword">this</span>.linkRef&#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">WrappedComponent</span> &#123;<span class="attr">...props</span>&#125;/&gt;</span></span></span><br><span class="line"><span class="xml">    &#125;</span></span><br><span class="line"><span class="xml">  &#125;</span></span><br><span class="line"><span class="xml">&#125;</span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">export default refsHOC</span></span><br></pre></td></tr></table></figure>
<p>这个refs高阶组件的工作原理其实也是增加传递给被包裹组件的props，不同的是利用了ref这个特殊的prop而已。我们通过linkRef来给被包裹组件传递ref值，linkRef被调用时，我们就可以得到被包裹组件的DOM实例。</p>
<p>这种高阶组件在用途上来讲可以说是无所不能的，因为只要能够获得对被包裹组件的引用，就能通过这个引用任意操纵一个组件的DOM元素，贼酸爽。但它从某个角度来讲也是啥也干不了的，因为react团队表示：<strong>不要过度使用 Refs</strong>。且我们也有更好的替代品——控制组件（Controlled Component)来解决相关问题，因此这个坑建议大家还是尽量少踩为好。</p>
<h3 id="抽取状态"><a href="#抽取状态" class="headerlink" title="抽取状态"></a>抽取状态</h3><p>对于抽取状态，我想大家应该都不会很陌生。react-redux中的connect函数就实现了这种功能，它异常的强大，也成功吸引了我对高阶组件的注意。但在这有一点需要明确的是：connect函数本身并不是高阶组件，connect函数执行的结果才是一个高阶组件。让我们来看看connect的源码的主要逻辑：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">connect</span>(<span class="params">mapStateToProps, mapDispatchToProps, mergeProps, options = &#123;&#125;</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">wrapWithConnect</span>(<span class="params">WrappedComponent</span>) </span>&#123;</span><br><span class="line">        <span class="class"><span class="keyword">class</span> <span class="title">Connect</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">            <span class="keyword">constructor</span>(props, context) &#123;</span><br><span class="line">                <span class="comment">//参数获取</span></span><br><span class="line">                <span class="keyword">super</span>(props, context)</span><br><span class="line">                <span class="keyword">this</span>.store = props.store || context.store</span><br><span class="line">                <span class="keyword">const</span> storeState = <span class="keyword">this</span>.store.getState()</span><br><span class="line">                <span class="keyword">this</span>.state = &#123; storeState &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 进行判断，当数据发生改变时，Component重新渲染</span></span><br><span class="line">            shouldComponentUpdate(nextProps, nextState) &#123;</span><br><span class="line">                <span class="keyword">if</span> (propsChanged || mapStateProducedChange || dispatchPropsChanged) &#123;</span><br><span class="line">                 <span class="keyword">this</span>.updateState(nextProps)</span><br><span class="line">                  <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">                 &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            <span class="comment">// 改变Component中的state</span></span><br><span class="line">            componentDidMount() &#123;</span><br><span class="line">                 <span class="keyword">this</span>.store.subscribe(() = &#123;</span><br><span class="line">                  <span class="keyword">this</span>.setState(&#123;</span><br><span class="line">                   storeState: <span class="keyword">this</span>.store.getState()</span><br><span class="line">                  &#125;)</span><br><span class="line">                 &#125;)</span><br><span class="line">                &#125;</span><br><span class="line">            render()&#123;</span><br><span class="line">                <span class="keyword">this</span>.renderedElement = createElement(WrappedComponent,</span><br><span class="line">                    <span class="keyword">this</span>.mergedProps</span><br><span class="line">                )</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">this</span>.renderedElement</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> hoistStatics(Connect, WrappedComponent)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>从上面的代码我们不难看出connect模块的返回值wrapWithConnect是一个函数，而这个函数才是我们所认知的高阶组件。wrapWithConnect函数会返回一个ReactComponent对象Connect，Connect会重新render外部传入的原组件WrappedComponent，并把connect中所传入的mapStateToProps, mapDispatchToProps和this.props合并后结合成一个对象，通过属性的方式传给WrappedComponent，这才是最终的渲染结果。</p>
<h3 id="包装组件"><a href="#包装组件" class="headerlink" title="包装组件"></a>包装组件</h3><p>在日常开发中我们所接触到的大多数的高阶组件都是通过修改props部分来对输入的组件进行相对增强的。但其实高阶组件还有其他的方式来增强组件，比如我们可以通过在render函数中的JSX引入其他元素，甚至将多个react组件合并起来，来获得更骚气的样式或方法，例如我们可以给组件增加style来改变组件样式：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> styleHOC = <span class="function">(<span class="params">WrappedComponent, style</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="class"><span class="keyword">class</span> <span class="title">HOCComponent</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">        render() &#123;</span><br><span class="line">            <span class="keyword">return</span> (</span><br><span class="line">            &lt;div style=&#123;style&#125;&gt;</span><br><span class="line">                &lt;WrappedComponent &#123;...this.props&#125; /&gt;</span><br><span class="line">            &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">            )</span></span><br><span class="line"><span class="regexp">        &#125;</span></span><br><span class="line"><span class="regexp">    &#125;</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure></p>
<p>当我们想改变组件的样式的时候，我们就可以直接调用这个函数，比如这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> style = &#123;</span><br><span class="line">			background-color: #f1fafa;</span><br><span class="line">			font-family: <span class="string">"微软雅黑"</span>;</span><br><span class="line">			font-size: <span class="number">20</span>px;</span><br><span class="line">		&#125;</span><br><span class="line"><span class="keyword">const</span> BeautifulComponent = styleHOC(uglyComponent, style)</span><br></pre></td></tr></table></figure>
<h2 id="继承方式的高阶组件"><a href="#继承方式的高阶组件" class="headerlink" title="继承方式的高阶组件"></a>继承方式的高阶组件</h2><p>前面我们讨论了代理方式实现的高阶组件以及它们的主要使用方式，现在我们继续来讨论一下以继承方式实现的高阶组件。</p>
<p>。继承方式的高阶组件通过继承来关联作为参数传入的组件和返回的组件，比如传入的组件参数是OldComponent,那函数所返回的组件就直接继承于OldComponemt。</p>
<p>码界有句老话说的好：组合优于继承。在高阶组件里也不例外。<br>继承方式的高阶组件相对于代理方式的高阶组件有很多不足之处，比如输入的组件与输出的组件共有一个生命周期等，因此通常我们接触到的高阶组件大多是代理方式实现的高阶组件，也推荐大家首先考虑以代理方式来实现高阶组件。但我们还是需要去了解并学习它，毕竟它也是有可取之处的，比如在操作生命周期函数上它还是具有其优越性的。</p>
<h3 id="操作生命周期函数"><a href="#操作生命周期函数" class="headerlink" title="操作生命周期函数"></a>操作生命周期函数</h3><p>说继承方式的高阶组件在操纵生命周期函数上有其优越性其实不够说明它在这个领域的地位，更准确地表达是：操作生命周期函数是继承方式的高阶组件所特有的功能。这是由于继承方式的高阶组件返回的新组件继承于作为参数传入的组件，两个组件的生命周期是共用的，因此可以重新定义组件的生命周期函数并作用于新组件。而代理方式的高阶组件作为参数输入的组件与输出的组件完全是两个生命周期，因此改变生命周期函数也就无从说起了。</p>
<p>例如我们可以定义一个让参数组件只有在用户登录时才显示的高阶组件：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> shouldLoggedInHOC = <span class="function">(<span class="params">WrappedComponent</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="class"><span class="keyword">class</span> <span class="title">MyComponent</span> <span class="keyword">extends</span> <span class="title">WrappedComponent</span> </span>&#123;</span><br><span class="line">        render() &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.props.loggedIn) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">super</span>.render()</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">null</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="操纵Prop"><a href="#操纵Prop" class="headerlink" title="操纵Prop"></a>操纵Prop</h3><p>除了操作生命周期函数外，继承方式的高阶函数也能对Prop进行操作，但总的难说贼麻烦，当然也有简单的方式，比如这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">removeProps</span>(<span class="params">WrappedComponent</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="class"><span class="keyword">class</span> <span class="title">NewComponent</span> <span class="keyword">extends</span> <span class="title">WrappedComponent</span> </span>&#123;</span><br><span class="line">        render() &#123;</span><br><span class="line">        <span class="keyword">const</span>&#123; user, ...otherProps &#125; = <span class="keyword">this</span>.props</span><br><span class="line">        <span class="keyword">this</span>.props = otherProps</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">super</span>.render()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>虽然这样看起来很简单，但我们直接修改了this.props，这不是一个好的实践，可能会产生不可预料的后果，更好的操作办法是这样的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">removeProps</span>(<span class="params">WrappedComponent</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="class"><span class="keyword">class</span> <span class="title">NewComponent</span> <span class="keyword">extends</span> <span class="title">WrappedComponent</span> </span>&#123;</span><br><span class="line">        render() &#123;</span><br><span class="line">        <span class="keyword">const</span> element =<span class="keyword">super</span>.render()</span><br><span class="line">        <span class="keyword">const</span>&#123; user, ...otherProps &#125; = <span class="keyword">this</span>.props</span><br><span class="line">        <span class="keyword">this</span>.props = otherProps</span><br><span class="line">        <span class="keyword">return</span> React.cloneElement(element, <span class="keyword">this</span>.props, element.props.children)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以通过React.cloneElement来传入新的props，让这些产生的组件重新渲染一次。但虽然这种方式可以解决直接修改this.props所带来的问题，但实现起来贼麻烦，唯一用得上的就是高阶组件需要根据参数组件WrappedComponent渲染结果来决定如何修改props时用得上，其他的时候显然使用代理模式更便捷清晰。</p>
<h2 id="高阶组件命名"><a href="#高阶组件命名" class="headerlink" title="高阶组件命名"></a>高阶组件命名</h2><p>用 HOC 包裹了一个组件会使它失去原本 WrappedComponent 的名字，可能会影响开发和debug。</p>
<p>因此我们通常会用 WrappedComponent 的名字加上一些 前缀作为 HOC 的名字。我们来看看React-Redux是怎么做的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getDisplayName</span>(<span class="params">WrappedComponent</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> WrappedComponent.displayName ||</span><br><span class="line">         WrappedComponent.name ||</span><br><span class="line">         ‘Component’</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">HOC.displayName = <span class="string">`HOC(<span class="subst">$&#123;getDisplayName(WrappedComponent)&#125;</span>)`</span></span><br><span class="line"><span class="comment">//或</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HOC</span> <span class="keyword">extends</span> ... </span>&#123;</span><br><span class="line">  <span class="keyword">static</span> displayName = <span class="string">`HOC(<span class="subst">$&#123;getDisplayName(WrappedComponent)&#125;</span>)`</span></span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实际上我们不用自己来写getDisplayName这个函数，recompose 提供了这个函数，我们只要使用即可。</p>
<h4 id="结尾语"><a href="#结尾语" class="headerlink" title="结尾语"></a>结尾语</h4><p>我们其他要注意的就是<a href="https://react.bootcss.com/react/docs/higher-order-components.html" target="_blank" rel="noopener">官方文档</a>所说的几个约定与相关规范，在此我就不一一赘述了，感兴趣的可以自己去看看。最后很感谢能看到这里的朋友，因为水平有限，如果有错误敬请指正，十分感激！</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/React/" rel="tag"># React</a>
          
            <a href="/blog/tags/高阶组件/" rel="tag"># 高阶组件</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/05/06/4.表单组件/" rel="next" title="4.表单组件">
                <i class="fa fa-chevron-left"></i> 4.表单组件
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/05/06/1.JSX初识/" rel="prev" title="1.JSX初识">
                1.JSX初识 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#初识高阶组件"><span class="nav-number"></span> <span class="nav-text">初识高阶组件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#高阶组件的实现分类"><span class="nav-number"></span> <span class="nav-text">高阶组件的实现分类</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#代理方式的高阶组件"><span class="nav-number"></span> <span class="nav-text">代理方式的高阶组件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#控制prop"><span class="nav-number"></span> <span class="nav-text">控制prop</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通过ref获取组件实例"><span class="nav-number"></span> <span class="nav-text">通过ref获取组件实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#抽取状态"><span class="nav-number"></span> <span class="nav-text">抽取状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#包装组件"><span class="nav-number"></span> <span class="nav-text">包装组件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#继承方式的高阶组件"><span class="nav-number"></span> <span class="nav-text">继承方式的高阶组件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#操作生命周期函数"><span class="nav-number"></span> <span class="nav-text">操作生命周期函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#操纵Prop"><span class="nav-number"></span> <span class="nav-text">操纵Prop</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#高阶组件命名"><span class="nav-number"></span> <span class="nav-text">高阶组件命名</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#结尾语"><span class="nav-number">1.</span> <span class="nav-text">结尾语</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
